#!/bin/bash

# 提示输入源数据库连接信息
read -p "请输入源数据库的Host: " db_src_host
read -sp "请输入源数据库的密码: " db_src_password
echo

# 提示输入目标数据库连接信息
read -p "请输入目标数据库的Host: " db_dest_host
read -sp "请输入目标数据库的密码: " db_dest_password
echo

db_src_port="30001"
db_src_user="root"
db_dest_port="30001"
db_dest_user="root"

# 读取数据库列表
db_list_file="mariadb_list"

# 检查数据库列表文件是否存在
if [ ! -f "$db_list_file" ]; then
  echo "数据库列表文件 $db_list_file 不存在"
  exit 1
fi

# 循环处理数据库列表中的每个数据库
while read db_name; do
  if [ -z "$db_name" ]; then
    continue
  fi
  
  # 导出数据库，包含CREATE DATABASE和USE语句
  echo "正在导出数据库: $db_name"
  mysqldump -h "$db_src_host" -P "$db_src_port" -u "$db_src_user" -p"$db_src_password" --databases "$db_name" --skip-lock-tables --no-tablespaces > "$db_name.sql"
  if [ $? -ne 0 ]; then
    echo "导出数据库 $db_name 失败"
    continue
  fi

  # 在SQL文件前添加 CREATE DATABASE 和 USE 语句
  echo "CREATE DATABASE IF NOT EXISTS \`$db_name\`;" > "$db_name.sql.temp"
  echo "USE \`$db_name\`;" >> "$db_name.sql.temp"
  cat "$db_name.sql" >> "$db_name.sql.temp"
  mv "$db_name.sql.temp" "$db_name.sql"

  # 替换SQL文件中的 db_src_host 为 db_dest_host
  sed -i "s/$db_src_host/$db_dest_host/g" "$db_name.sql"

  # 导入数据库
  echo "正在导入数据库: $db_name"
  mysql -h "$db_dest_host" -P "$db_dest_port" -u "$db_dest_user" -p"$db_dest_password" < "$db_name.sql"
  if [ $? -ne 0 ]; then
    echo "导入数据库 $db_name 失败"
  else
    echo "数据库 $db_name 导入成功"
  fi

  # 清理导出的SQL文件
  rm -f "$db_name.sql"
done < "$db_list_file"

echo "迁移操作完成"
